<template>
  <div><h1>商品列表</h1></div>
  <div>
    <el-form :inline="true" :model="from" class="demo-form-inline">
      <el-form-item label="关键字">
        <el-input v-model="from.keyWord" placeholder="请输入关键字" clearable />
      </el-form-item>
      <el-form-item label="ID">
        <el-input v-model="from.id" placeholder="请输入商品ID" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="listHh()">查询</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div>
    <el-button type="success" @click="handleAddProd()">添加商品</el-button>
  </div>
  <div>
    <el-button type="info" @click="deleteAllFrom()">批量删除</el-button>
  </div>
  <div>
    <el-table
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="prodId" label="商品ID" width="180" />
      <el-table-column prop="prodSpu" label="商品SPU" width="180" />
      <el-table-column prop="prodName" label="商品名称" />

      <el-table-column prop="prodImage" label="商品缩略图">
        <template #default="scope">
          <el-avatar
            v-if="scope.row.prodImage != null"
            :src="scope.row.prodImage"
            shape="square"
            :size="100"
          />
        </template>
      </el-table-column>
      <el-table-column prop="typeName" label="商品分类" />
      <el-table-column prop="brandName" label="品牌ID" />
      <el-table-column prop="unitName" label="商品单位" />
      <el-table-column prop="tagName" label="商品标签" />
      <el-table-column prop="apprName" label="供应商ID" />
      <el-table-column prop="prodStatus" label="商品状态">
        <template #default="scope">
          <el-tag type="info" v-if="scope.row.prodStatus == 0">未上架</el-tag>
          <el-tag type="success" v-if="scope.row.prodStatus == 1"
            >已上架</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="kindName" label="商品类型" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column prop="createBy" label="创建人" />
      <el-table-column prop="updateTime" label="更新时间" />
      <el-table-column prop="updateBy" label="更新人" />

      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click="handleBuyClick(scope.row)"
          >
            购买
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            @click="handleClick(scope.row)"
          >
            商品
          </el-button>
          <el-button
            link
            type="success"
            @click="handleAtta(scope.row)"
            size="small"
            >商品附件</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div>
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="from.pageNum"
        v-model:page-size="from.pageSize"
        :page-sizes="[2, 4, 6, 8]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
  <div>
    <el-dialog v-model="dialogFormVisible" title="修改弹出框" width="500">
      <el-form :model="form" ref="ruleFormRef" :rules="rules">
        <el-form-item
          label="商品类型"
          :label-width="formLabelWidth"
          prop="kindId"
        >
          <div class="mb-2 ml-4">
            <el-radio-group v-model="form.kindId">
              <el-radio value="0" size="large">实物商品</el-radio>
              <el-radio value="1" size="large">虚拟商品</el-radio>
              <el-radio value="2" size="large">卡密/网盘</el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item label="商品分类" :label-width="formLabelWidth">
          <el-tree-select
            v-model="form.typeId"
            :data="typeListTree"
            check-strictly
            :render-after-expand="false"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item
          label="商品名称"
          :label-width="formLabelWidth"
          prop="prodName"
        >
          <el-input v-model="form.prodName" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="商品SPU"
          :label-width="formLabelWidth"
          prop="prodSpu"
        >
          <el-input v-model="form.prodSpu" autocomplete="off" />
        </el-form-item>
        <el-form-item label="商品品牌" :label-width="formLabelWidth">
          <el-select
            v-model="form.brandId"
            placeholder="请选择"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in brandListAll"
              :key="item.brandId"
              :label="item.brandName"
              :value="item.brandId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品单位" :label-width="formLabelWidth">
          <el-select
            v-model="form.unitId"
            placeholder="请选择"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in unitListAll"
              :key="item.unitId"
              :label="item.unitName"
              :value="item.unitId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品标签" :label-width="formLabelWidth">
          <el-select
            v-model="form.tagId"
            placeholder="请选择"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in tagListAll"
              :key="item.tagId"
              :label="item.tagName"
              :value="item.tagId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" :label-width="formLabelWidth">
          <el-select
            v-model="form.apprId"
            placeholder="请选择"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in apprListAll"
              :key="item.apprId"
              :label="item.apprName"
              :value="item.apprId"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="商品缩略图"
          :label-width="formLabelWidth"
          prop="prodImage"
        >
          <el-upload
            class="avatar-uploader"
            action="http://localhost:10010/user/index/uploadFile"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :headers="headers"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            添加
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>

  <div>
    <el-dialog v-model="dialogFormVisibleTwo" title="商品附件" width="800">
      <el-form :model="form">
        <el-form-item label="商品轮播图" :label-width="formLabelWidth">
          <el-upload
            v-model:file-list="fileList"
            action="http://localhost:10010/user/index/uploadFile"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :headers="headers"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="商品视频" :label-width="formLabelWidth">
          <el-upload
            v-model:file-list="mobeList"
            class="upload-demo"
            action="http://localhost:10010/user/index/uploadFile"
            :on-change="handleChange"
            :headers="headers"
            :before-upload="beforeAvatarUpload"
          >
            <el-button type="primary">上传视频</el-button>
            <template #tip>
              <div class="el-upload__tip">
                作用于商品详情页顶部轮错的视频结束，最大限制20MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="上架时间" :label-width="formLabelWidth">
          <el-radio-group v-model="attaFrom.upType">
            <el-radio :value="0">立即上架</el-radio>
            <el-radio :value="1">定时上架</el-radio>
          </el-radio-group>
          <el-form-item
            label=""
            :label-width="formLabelWidth"
            v-if="attaFrom.upType == 1"
          >
            <el-date-picker
              v-model="attaFrom.upTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择上架时间"
            />
          </el-form-item>
        </el-form-item>
        <el-form-item label="定时下架" :label-width="formLabelWidth">
          <el-switch
            v-model="attaFrom.downType"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item
          label=""
          :label-width="formLabelWidth"
          v-if="attaFrom.downType == 1"
        >
          <el-date-picker
            v-model="attaFrom.upTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择下架时间"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisibleTwo = false">放弃</el-button>
          <el-button type="primary" @click="onSubmitAddAtta()">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
const tableData = ref([]);
const multipleSelection = ref<any[]>([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
import type { UploadProps, UploadUserFile } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";

import { onMounted, ref } from "vue";
import {
  selectList,
  updateFile,
  deleteById,
  deleteAll,
  getProdList,
  getApprListAll,
  getBrandListAll,
  getUnitListAll,
  getTagListAll,
  getTypeSelectTree,
  addProd,
  deleteAllProd,
  addProdAtta,
} from "../api/api";
import type { ComponentSize } from "element-plus";

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
  console.log(multipleSelection.value);
};

const ruleFormRef = ref<FormInstance>();

/**
 * 视频校验
 */
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  console.log("beforeAvatarUpload", rawFile.type);

  if (rawFile.type !== "video/mp4") {
    ElMessage.error("上传文件的视频必须为视频!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("上传文件不能大于2Mb!");
    return false;
  }
  return true;
};
/**
 * 添加表单校验
 */
const rules = reactive<FormRules<any>>({
  prodName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  prodSpu: [{ required: true, message: "请输入商品Spu", trigger: "blur" }],
  kindId: [{ required: true, message: "请选择商品类型", trigger: "change" }],
  prodImage: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (imageUrl.value == null || imageUrl.value == "") {
          // 提示错误
          callback(new Error("请上传商品图片"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      addProdList();
      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};

/**
 * 视频上传
 */
const mobeList = ref<UploadUserFile[]>([]);

const handleChange: UploadProps["onChange"] = (uploadFile, uploadFiles) => {
  console.log("mobelist", mobeList.value);
  mobeList.value = mobeList.value.slice(-3);
};

// 多图片上传
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const fileList = ref<UploadUserFile[]>([]);

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  console.log("handLePictureCardPreview", uploadFile);

  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

const typeListTree = ref([]);
const brandListAll = ref([]);
const unitListAll = ref([]);
const tagListAll = ref([]);
const apprListAll = ref([]);

// const selectable = (row: any) => ![1, 2].includes(row.id);
const imageUrl = ref("");
import { ElMessage, ElMessageBox } from "element-plus";
import { round } from "echarts/types/src/util/number.js";
import router from "@/router";
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl.value = response.data;
};
const update = () => {
  form.value.userAvatar = imageUrl.value;
  updateFile(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("修改成功");
      dialogFormVisible.value = false;
      listHh();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};
// 商品附件
const handleAtta = (row: any) => {
  console.log("row", row);
  attaFrom.value.prodId = row.prodId;
  dialogFormVisibleTwo.value = true;
};

/**
 * 购买
 */
const handleBuyClick = (row: any) => {
  // 存入当前信息
  console.log("handleBuyProd", row);
  let prod = JSON.stringify(row);
  sessionStorage.setItem("buy", prod);
  router.push("/home/buy");
};
/**
 * 添加商品附件表
 */
const onSubmitAddAtta = () => {
  // 轮播图数组放入表单
  attaFrom.value.imageList = [];
  fileList.value.forEach((item) => {
    console.log("item", item);
    attaFrom.value.imageList.push(item.response.data);
  });

  // 商品视频放入表单
  if (mobeList.value.length > 0) {
    attaFrom.value.prodVideo = mobeList.value[0].response.data;
  }

  // 提交
  addProdAtta(attaFrom.value).then((res) => {
    if (res.data.code == 200) {
      dialogFormVisibleTwo.value = false;
      ElMessage.success("添加商品附件成功");
      listHh();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

const addProdList = () => {
  form.value.prodImage = imageUrl.value;
  addProd(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      dialogFormVisible.value = false;
      listHh();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

const headers = ref({
  token: sessionStorage.getItem("token") || "",
});

const attaFrom = ref({
  downTime: "",
  downType: 0,
  imageList: [],
  prodId: 0,
  prodVideo: "",
  upTime: "",
  upType: 0,
});

const restFrom = () => {
  form.value = {
    apprId: null,
    brandId: null,
    createBy: "",
    createTime: "",
    kindId: null,
    prodId: null,
    prodImage: null,
    prodName: "",
    prodSpu: "",
    prodStatus: null,
    tagId: null,
    typeId: null,
    unitId: null,
    updateBy: "",
    updateTime: "",
  };
  imageUrl.value = "";
};

const form = ref({
  apprId: null,
  brandId: null,
  createBy: "",
  createTime: "",
  kindId: null,
  prodId: null,
  prodImage: null,
  prodName: "",
  prodSpu: "",
  prodStatus: null,
  tagId: null,
  typeId: null,
  unitId: null,
  updateBy: "",
  updateTime: "",
});

// 添加商品
const handleAddProd = () => {
  restFrom();
  dialogFormVisible.value = true;
};
// 修改商品
const handleClick = (any: any) => {
  dialogFormVisible.value = true;
  Object.assign(form.value, any);
  imageUrl.value = form.value.prodImage;
};
const from = ref({
  beginTime: "",
  endTime: "",
  gender: null,
  keyWord: "",
  pageNum: 1,
  pageSize: 2,
  id: null,
});
const total = ref(0);
const size = ref<ComponentSize>("default");
const background = ref(false);
const disabled = ref(false);
const dialogFormVisible = ref(false);
const dialogFormVisibleTwo = ref(false);
const formLabelWidth = "140px";

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  from.value.pageSize = val;
  listHh();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  from.value.pageNum = val;
  listHh();
};

const deleteFrom = (userId: number) => {
  deleteById(userId).then((res) => {
    ElMessageBox.confirm("您确定要删除吗?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        //
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          listHh();
        } else {
          ElMessage.error(res.data.msg);
        }
      })
      .catch(() => {});
  });
};

/**
 * 批量删除
 */

const deleteAllFrom = () => {
  if (multipleSelection.value.length == 0) {
    ElMessage.error("请选择要删除的商品");
    return;
  }

  deleteAllProd(multipleSelection.value).then((res) => {
    ElMessageBox.confirm("您确定要删除吗?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        //
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          listHh();
        } else {
          ElMessage.error(res.data.msg);
        }
      })
      .catch(() => {});
  });
};
// 钩子函数
onMounted(() => {
  // 获取商品类型树
  getTypeSelectTree().then((res) => {
    if (res.data.code == 200) {
      console.log(res.data.data);
      typeListTree.value = res.data.data;
    }
  });

  // 获取商品品牌列表
  getBrandListAll().then((res) => {
    if (res.data.code == 200) {
      brandListAll.value = res.data.data;
    }
  });

  // 获取商品单位列表
  getUnitListAll().then((res) => {
    if (res.data.code == 200) {
      unitListAll.value = res.data.data;
    }
  });

  // 获取商品标签列表
  getTagListAll().then((res) => {
    if (res.data.code == 200) {
      tagListAll.value = res.data.data;
    }
  });

  // 获取供应商列表
  getApprListAll().then((res) => {
    if (res.data.code == 200) {
      apprListAll.value = res.data.data;
    }
  });
});

const listHh = () => {
  getProdList(from.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};
listHh();
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
